package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper,Orders> implements OrderService {

    @Autowired
    WebSocketServer webSocketServer;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种异常(地址簿为空、购物车为空)
        AddressBook address = Db.getById(ordersSubmitDTO.getAddressBookId(), AddressBook.class);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserId(BaseContext.getCurrentId());

        if (address == null) {
            throw new DeletionNotAllowedException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        } else if (shoppingCarts.size() <= 0) {
            throw new DeletionNotAllowedException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //设置用户id
        orders.setUserId(BaseContext.getCurrentId());
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付状态 已支付
        orders.setPayStatus(Orders.PAID);
        //设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置订单状态为 待付款
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        //添加订单号 使用当前系统时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //添加手机号
        orders.setPhone(address.getPhone());
        //设置收货人
        orders.setConsignee(address.getConsignee());
        orders.setAddress(address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getDetail());
        //添加订单信息
        //这里要将id返回,因为下面添加订单明细表的时候需要添加当前的订单id
        orderMapper.insertOrder(orders);


        //向订单明细表插入n条调数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            //添加本次订单明细关联的订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //批量插入数据
        orderDetailMapper.insertBatch(orderDetailList);

        //下单成功后,清空购物车数据
        shoppingCartMapper.cleanAllByUserId(BaseContext.getCurrentId());

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber()).build();

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号,"+orders.getId());

        //发送
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);


        return orderSubmitVO;
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //查询所有订单基本信息
        Long userId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setStatus(ordersPageQueryDTO.getStatus());
        //因为分页查询主要依据订单基本信息,所以设置一页查多少和一共几页由查询订单基本信息决定
        //因此在查询订单基本信息时完成分页
        Page<Orders> page = orderMapper.pageQuery(orders);

        List<OrderVO> ordersVOS = new ArrayList<>();
        //遍历所有订单基本信息,每个订单对应着一个详细信息,根据订单id进行查找,一一匹配
        //最后将匹配好的数据封装为ordersDTO存入数组中
        for (Orders order : page) {
            OrderVO ordersVO = new OrderVO();
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            BeanUtils.copyProperties(order, ordersVO);
            ordersVO.setOrderDetailList(orderDetails);
            ordersVOS.add(ordersVO);
        }
        //这里的数据部分就是查询的全部结果
        return new PageResult(page.getTotal(), ordersVOS);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void oneMoreOrder(Integer id) {
        //查询需要再来一单的样单信息
        List<OrderDetail> orderDetailListCopy = orderDetailMapper.selectByOrderId(BaseContext.getCurrentId());
        //清空购物车
        shoppingCartMapper.cleanAllByUserId(BaseContext.getCurrentId());

        //将订单基本信息传入购物车
        for (OrderDetail orderDetail : orderDetailListCopy) {
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }


    /**
     * 用户取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrderByUser(Integer id) {
        //查询要被取消的订单信息
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        Orders cancelOrder = orderMapper.select(orders);

        //判断订单状态
        if (cancelOrder == null) {
            throw new DeletionNotAllowedException(MessageConstant.ORDER_NOT_FOUND);
        } else if (cancelOrder.getStatus() > 2) {
            throw new DeletionNotAllowedException(MessageConstant.ORDER_STATUS_ERROR);
        } else if (cancelOrder.getStatus() == Orders.PENDING_PAYMENT) {
            if (cancelOrder.getStatus() == Orders.TO_BE_CONFIRMED) {
                //如果订单处于待接单状态需要给用户退款
                cancelOrder.setPayStatus(Orders.REFUND);
            }
            //如果订单处于待付款状态,则可以取消
            //将订单状态修改为已取消状态
            cancelOrder.setStatus(Orders.CANCELLED);
            orders.setCancelReason("用户取消");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(cancelOrder);
        }

    }


    /**
     * 查看订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrders(Integer id) {
        //查询当前订单基本信息
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        Orders order = orderMapper.select(orders);

        //查询当前订单详细信息
        List<OrderDetail> list = orderDetailMapper.selectByOrderId(order.getId());

        //将数据封装进OrdersDTO中返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancleOrderByAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        //查询被取消的订单信息
        Orders order = orderMapper.select(orders);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        // 订单处于待接单状态下取消，需要进行退款
        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderById(Integer id) {
        //查询订单基本信息
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        Orders order = orderMapper.select(orders);

        //根据订单id查询订单详细信息
        List<OrderDetail> list = orderDetailMapper.selectByOrderId(Long.valueOf(id));

        //将所有订单信息封装进OrderVO中
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void deliveryOrderById(Integer id) {
        //查询派送的订单信息
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        Orders order = orderMapper.select(orders);
        //判断当前订单状态是否为待派送
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);

    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //查询派送的订单信息
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        Orders order = orderMapper.select(orders);

        if (order.getStatus() == Orders.TO_BE_CONFIRMED) {
            //将状态设置为已接单
            order.setStatus(Orders.CONFIRMED);
            orderMapper.update(order);
        } else {
            throw new DeletionNotAllowedException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }


    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void completeOrder(Integer id) {
        //查询派送的订单信息
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        Orders order = orderMapper.select(orders);
        //判断当前订单状态是否为派送中
        if (order == null || order.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new DeletionNotAllowedException(MessageConstant.ORDER_NOT_FOUND);
        }
            //将状态设置为已完成
            order.setDeliveryTime(LocalDateTime.now());

            order.setStatus(Orders.COMPLETED);
            orderMapper.update(order);


    }


    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());
        //查询被取消的订单信息
        Orders order = orderMapper.select(orders);
        //判断被删除的订单状态是否为已支付
        if (order == null) {
            throw new DeletionNotAllowedException(MessageConstant.ORDER_NOT_FOUND);
        } else if (order.getStatus() == Orders.TO_BE_CONFIRMED) {
            if (order.getPayStatus() == Orders.PAID) {
                //用户已经付款,需要将钱退还
                order.setPayStatus(Orders.REFUND);

            }
            //设置取消原因和取消时间
            order.setStatus(Orders.CANCELLED);
            order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            order.setCancelTime(LocalDateTime.now());
            orderMapper.update(order);
        }
    }


    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO selectOrderStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //查询各种状态下订单的数量
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //封装入OrderStatisticsVO中返回
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult searchOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersPageQueryDTO, orders);
        Page<Orders> page = orderMapper.pageQuery(orders);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 用户催单功能
     * 当用户催单时，本方法会被调用，以通知相关方订单需要加快处理
     *
     * @param id 订单ID，用于标识特定的订单
     */
    @Override
    public void reminder(Integer id) {
        //查询订单信息
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        Orders order = orderMapper.select(orders);
        if (order == null){
            //如果订单不存在，抛出异常提示用户
            throw new DeletionNotAllowedException(MessageConstant.ORDER_NOT_FOUND);
        }

        //通过websocket向客户端浏览器推送消息
        Map map =new HashMap();
        map.put("typr",2);//1:来单提醒  2:客户催单
        map.put("orderId",id);
        map.put("content","订单号"+order.getNumber());

        //将打包好的数据通过websocket推送至浏览器
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);//约定只能传json字符串
    }


    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    /*@Override
    public OrderPaymentVO paymentOrders(OrdersPaymentDTO ordersPaymentDTO) {

    }*/

}
